package com.jrx.anytxn.transaction.job.paph.step;

import com.jrx.anytxn.transaction.bean.PaphFileBean;
import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.service.IPaphFileService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PlanFileWriter implements ItemWriter<PaphFileBean> {

    @Autowired
    private PaphFileConfig paphFileConfig;

    @Autowired
    private IPaphFileService paphFileService;

    @Override
    public void write(List<? extends PaphFileBean> items) throws Exception {

        if(CollectionUtils.isNotEmpty(items)){
            Map<String,List<PaphFileBean>> map = items.stream().collect(Collectors.groupingBy(PaphFileBean::getProductType));
            map.forEach(
                    (productType,list) -> {
                        List<String> messageList = list.stream().map(PaphFileBean::getFileString).collect(Collectors.toList());
                        paphFileService.generateFile(messageList, paphFileConfig.getPlanFilePath(),
                                TransBizConstant.PLAN_FILE_NAME, paphFileConfig.getFileType(),productType);
                    }
            );

        }
    }
}
